package com.ds.common.id;

import cn.hutool.core.util.IdUtil;
import org.apache.commons.lang3.StringUtils;

/**
 * @class: DistributeID
 * @description: 分布式ID
 * @author: fs
 * @create: 2024/9/13 18:20
 **/
public class DistributeID {

    public static String generate(BusinessCode businessCode, String externalId, long sequence) {
        int table = externalId.hashCode() % businessCode.getTableCount();
        String suffix = StringUtils.leftPad(String.valueOf(table), 4, "0");
        return String.valueOf(businessCode.getCode()) + sequence + suffix;
    }

    public static String generateWithSnowflake(BusinessCode businessCode, long workerId, String externalId) {
        long id = IdUtil.getSnowflake(workerId).nextId();
        return generate(businessCode, externalId, id);
    }

    public static String generateWithSnowflake(BusinessCode businessCode) {
        long id = IdUtil.getSnowflake().nextId();
        return String.valueOf(businessCode.getCode()) + id;
    }

    //public static void main(String[] args) {
    //    System.out.println(generateWithSnowflake(BusinessCode.USER));
    //    System.out.println(generateWithSnowflake(BusinessCode.TRADE_ORDER, 12, "dfsadfa"));
    //}
}
